package com.adwin.addcoin.utils

import android.content.Context
import com.adwin.addcoin.repository.SchedulerTransformer
import com.adwin.addcoin.repository.api.TestApi
import com.adwin.addcoin.repository.net.RetrofitClient
import com.cashbird.app.infra.utils.FlowBus
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.launch
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.json.JSONArray
import org.json.JSONObject
import java.util.concurrent.atomic.AtomicBoolean

object TaskStatusNet {
    private var taskMap = HashMap<Long,Long>()
    private var mContext:Context? = null
    private var isNet = AtomicBoolean(false)


    fun initTaskStage(context:Context){
        MainScope().launch(Dispatchers.IO){
            mContext = context
            val taskOffer = context.getTaskArray()
            val jsonArray = JSONArray(taskOffer)
            for (i in 0 until jsonArray.length()){
                val obt = jsonArray.getJSONObject(i)
                val taskid = obt.optLong("taskId",0)
                val coins = obt.optLong("coins",0)
                taskMap[taskid] = coins
            }
        }
    }

    fun addTaskStage(stepNum:Long,coins:Long){
        if (taskMap.contains(stepNum))return
        taskMap[stepNum] = coins
        saveTaskData()
    }

    fun startStepStatus(){
        if (taskMap.size>0&& !isNet.get()){
            startTask()
        }
    }

    private fun startTask(){
        val map = JSONArray()

        taskMap.keys.forEachIndexed { index, key ->
            map.put(key)
        }
        isNet.set(true)
        val json = JSONObject()
        json.put("stepIds",map)
        val requestBody: RequestBody = MultipartBody.create(MediaType.get("application/json;charset=utf-8"), json.toString())
        RetrofitClient.getInstance().getService(TestApi::class.java)
            .queryTaskStatus(requestBody).compose(SchedulerTransformer()).subscribe({
                if (it.isSuccessful){
                    if (it.body()?.code == 200){
                        MainScope().launch(Dispatchers.IO) {
                            val results = it.body()?.data?.results?:return@launch
                            results?.forEach {
                                if (it.status == 1){
                                    val taskId = it.stepId.toLong()
                                    if (taskMap.contains(taskId)){
                                        val coins = taskMap.get(taskId)
                                        FlowBus.with<Long>(FlowKeyUtils.taskStageChange).post(coins?:0)
                                        taskMap.remove(taskId)
                                        saveTaskData()
                                    }
                                }
                            }
                        }
                    }
                }
                isNet.set(false)
            },{
                isNet.set(false)
            })
    }

    private fun saveTaskData(){
        MainScope().launch(Dispatchers.IO){
            var jsonArray = JSONArray()
            taskMap.keys.forEach { key ->
                val jsonobt = JSONObject()
                jsonobt.put("taskId",key)
                jsonobt.put("coins", taskMap[key])
                jsonArray.put(jsonobt)
            }
            mContext?.dataStore?.saveTaskArray(jsonArray.toString())
        }
    }
}